const express = require('express')
const bcryptjs = require('bcryptjs')
let server = express()

// 引入数据库相关的model文件
const PostUser = require('./models/user')

//req.body中间项的设置
server.use(express.json())
server.use(express.urlencoded({ extended: true }))

// 注册处理
server.post('/regY', async (req, res) => {
    res.header("Access-Control-Allow-Origin", "*")

    let username = req.body.username
    let password = req.body.password

    let users = await PostUser.findOne({ username })
    if(!users){
        password = await bcryptjs.hash(password, 12)
  
        let user = new PostUser({ username, password })
      
        try {
          await user.save()
          res.send({
            code: '1',
            msg: '注册成功'
          })
        } catch (error) {
          console.log(error)
          res.send({
            code: '-1',
            msg: '失败'
          })
        }
    }else{
        res.send({
            code: '-1',
            msg: '用户名已存在'
        })
    }
  })

  //登录处理
server.post('/logY', async (req, res) => {
    let username = req.body.username
    let password = req.body.password
    let bool = false
    // console.log(username)
    let user = await PostUser.findOne({ username })
    // console.log(user)
    if (user) {
      bool = await bcryptjs.compare(password, user.password)
    }
  
    if (bool) {
      res.send({
          code: '1',
          msg: '登录成功'
      })
    } else {
      res.send({
        code: '-1',
        msg: '失败'
      })
    }
  })

  server.listen(3000)
